﻿using Artech.Common;
using Artech.Core.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;

namespace Artech.Core.Resources.Configuration
{
    public class ResourcesSettings : ServiceLocatableConfigurationSection
    {
        private const string PropertyNameResourceProviders = "resourceProviders";
        private const string PropertyName4DefaultResourceProvider = "defaultResourceProvider";

        [ConfigurationProperty(PropertyName4DefaultResourceProvider, IsRequired = true)]
        public string DefaultResourceProvider
        {
            get { return (string)base[PropertyName4DefaultResourceProvider]; }
            set { base[PropertyName4DefaultResourceProvider] = value; }
        }

        [ConfigurationProperty(PropertyNameResourceProviders, IsRequired = true)]
        public NameTypeConfigurationElementCollection<ResourceProviderDataBase, CustomResourceProviderData> ResourceProviders
        {
            get
            {
                return (NameTypeConfigurationElementCollection<ResourceProviderDataBase, CustomResourceProviderData>)this[PropertyNameResourceProviders];
            }
            set
            {
                this[PropertyNameResourceProviders] = value;
            }
        }

        public override IEnumerable<TypeRegistration> GetRegistrations(IConfigurationSource configurationSource)
        {
            IEnumerable<TypeRegistration> typeRegistrations = this.ResourceProviders.SelectMany(provider => provider.GetRegistrations(configurationSource, this.DefaultResourceProvider));
            foreach (TypeRegistration registration in typeRegistrations)
            {
                yield return registration;
            }
        }

        public static ResourcesSettings GetSettings(IConfigurationSource configurationSource = null)
        {
            configurationSource = configurationSource ?? ConfigurationSourceFactory.Create();
            return configurationSource.GetSection(Constants.ConfigurationSections.Resources) as ResourcesSettings;
        }
    }
}
